package farmacia.dao;

import java.util.ArrayList;
import java.util.List;

import javax.management.Query;
import javax.transaction.Transaction;

import org.hibernate.Session;

import farmacia.hibernate.util.HibernateUtil;
import farmacia.model.Remedio;

public class RemedioDAOImplements implements IRemedioDAO {

	@Override
	public boolean InserirRemedio(Remedio remedio) {

		Session sessao = HibernateUtil.getSession();
		sessao.beginTransaction();

		try {
			sessao.save(remedio);
			sessao.getTransaction().commit();
		} catch (Exception e) {
			System.out.println("Erro ao inserir remedio!\n" + e);
			return false;
		} finally {
			sessao.close();
		}

		return true;
	}

	@Override
	public boolean AtualizarRemedio(Remedio remedio) {
		Session sessao = HibernateUtil.getSession();
		sessao.beginTransaction();

		try {
			sessao.update(remedio);
			sessao.getTransaction().commit();
		} catch (Exception e) {
			System.out.println("Erro ao atualizar remedio!\n" + e);
			return false;
		} finally {
			sessao.close();
		}

		return true;
	}

	@Override
	public boolean DeletarRemedio(Remedio remedio) {
		Session sessao = HibernateUtil.getSession();
		sessao.beginTransaction();

		try {
			sessao.delete(remedio);
			sessao.getTransaction().commit();
		} catch (Exception e) {
			System.out.println("Erro ao deletar remedio!\n" + e);
			return false;
		} finally {
			sessao.close();
		}

		return true;
	}

	@Override
	public Remedio RemedioPorId(Integer id) {
		Remedio remedio;
		Session sessao = HibernateUtil.getSession();
		sessao.beginTransaction();

		try {
			remedio = (Remedio) sessao.get(Remedio.class, id);
			sessao.getTransaction().commit();
		} catch (Exception e) {
			System.out.println("Erro ao buscar remedio!\n" + e);
			return null;
		} finally {
			sessao.close();
		}

		return remedio;
	}

	@Override
	public ArrayList<Remedio> ListarTodosRemedios() {
		ArrayList<Remedio> remedios;
		Session sessao = HibernateUtil.getSession();
		sessao.beginTransaction();

		try {

			remedios = (ArrayList<Remedio>) sessao.createQuery("from Remedio").list();
			sessao.getTransaction().commit();

		} catch (Exception e) {
			System.out.println("Erro ao listar remedios!\n" + e);
			return null;
		} finally {
			sessao.close();
		}

		return remedios;
	}

}
